<!doctype html>
<html>
  <head>
    <meta charset="utf8" />
    <title>Playback demo</title>
  </head>
  <body>
    <script type="text/javascript" src="../../dist/weasound.min.js"></script>

    <script type="text/javascript">
      let ac, playback, playbackType, workers;

      async function go() {
        const btn = document.getElementById("go");
        btn.onclick = void 0;

        const methodBox = document.getElementById("method");
        const method = methodBox.value;

        // Create a playback
        if (!ac) ac = new AudioContext();
        if (!playback || playbackType !== method) {
          playbackType = method;
          playback = await Weasound.createAudioPlayback(ac, {
            demandedType: method,
          });
          (playback.unsharedNode() || playback.sharedNode()).connect(
            ac.destination,
          );
        }

        let stop = false;
        btn.innerText = "Stop";
        btn.onclick = () => {
          stop = true;
          btn.innerText = "Play";
          btn.onclick = go;
        };

        // Play
        let si = 0;
        while (!stop) {
          // Create a frame
          const samples = new Float32Array(
            Math.floor(Math.random() * 1000) + 100,
          );
          for (let i = 0; i < samples.length; i++) {
            samples[i] = Math.sin((si / ac.sampleRate) * 600 * Math.PI);
            si++;
          }

          const latency = playback.play([samples]);
          console.log(`Estimated latency: ${latency}`);

          // Don't get too far ahead!
          if (latency > 200) await new Promise((res) => setTimeout(res, 100));
        }
      }
    </script>

    <label for="method">Playback type:</label>
    <select name="method" id="method">
      <option value="">Default</option>
      <option value="shared-awp">Shared AudioWorkletProcessor</option>
      <option value="shared-sp">Shared ScriptProcessor</option>
      <option value="ab">AudioBuffers</option>
      <option value="awp">Private AudioWorkletProcessor</option>
      <option value="sp">Private ScriptProcessor</option></select
    ><br />
    <button id="go">Play</button>
    <script type="text/javascript">
      document.getElementById("go").onclick = go;
    </script>
  </body>
</html>
